package com.yst.spring.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Slf4j
public class SpringContext {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getContext(){
        return applicationContext;
    }

    public interface IContextReady{
        void onReady(ApplicationContext context);
    }

    private static final List<IContextReady> listenerList=new ArrayList<>();
    public synchronized static void addOnReadyListener(IContextReady contextReady){
        listenerList.add(contextReady);
        if (Objects.nonNull(applicationContext)&&Objects.nonNull(contextReady)){
            contextReady.onReady(applicationContext);
        }
    }

    protected void doReady(){
        for(IContextReady contextReady:listenerList){
            try{
                if (Objects.nonNull(contextReady)) {
                    Objects.requireNonNull(contextReady).onReady(applicationContext);
                }
            }
            catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
    }

    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext=applicationContext;
        log.info(getClass().getName().concat("spring setApplicationContext success!"));
        doReady();
    }
}
